﻿@page "/login"
@using  BB.ViewModel.HomeVMs
@inherits BasePage

<div class="d-flex flex-column app-layout-login ">
    <div class="flex-fill  login-layout app-login-back-@bgnumber">
        <header class="login-header">
            <img src="/images/logo.png" alt="" height="48">
        </header>
        <div class="login-content">
            <div class="login-form">
                <h1>WTM Blazor</h1>
                <ValidateForm Model="@Model" OnValidSubmit="@Submit">
                    <BootstrapInput @bind-Value="@Model.ITCode" />
                    <BootstrapInput @bind-Value="@Model.Password" type="password" />
                    <Button ButtonType="ButtonType.Submit" Text="@WtmBlazor.Localizer["Login.Login"]" style="width:100%;margin-top:20px;" IsAsync="true" />
                </ValidateForm>
            </div>
        </div>
    </div>
</div>

<Toast />

@code {
    [Parameter]
    public bool? LoginSuccess { get; set; }
    [Parameter]
    public EventCallback<bool?> LoginSuccessChanged { get; set; }
    [Parameter]
    public EventCallback OnUserInfoSet { get; set; }

    private int bgnumber;
    private LoginVM Model = new LoginVM();

    protected override void OnInitialized()
    {
        bgnumber = new Random().Next(1, 6);
        if(WtmBlazor.ConfigInfo.IsQuickDebug == true)
        {
            Model.ITCode = "admin";
            Model.Password = "000000";
        }
        base.OnInitialized();
    }

    private async Task Submit(EditContext context)
    {
        var rv = await WtmBlazor.Api.CallAPI<DynamicData>("/api/_account/loginjwt", HttpMethodEnum.POST, new { Account = Model.ITCode, Password = Model.Password });
        if (rv.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var token = rv.Data.Fields["access_token"].ToString();
            var rtoken = rv.Data.Fields["refresh_token"].ToString();
            await SetToken(token,rtoken);
            var userinfo = await WtmBlazor.Api.CallAPI<LoginUserInfo>("/api/_account/CheckUserInfo", HttpMethodEnum.GET, new { });

            if (userinfo.StatusCode == System.Net.HttpStatusCode.OK)
            {
                await SetUserInfo(userinfo.Data);
                await OnUserInfoSet.InvokeAsync();
                await LoginSuccessChanged.InvokeAsync(true);
            }
            else
            {
                await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], rv.Errors.Message[0]);
            }

        }
        else
        {
            await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], rv.Errors?.Message[0]);
        }
    }
}
